<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="css/mui.css" rel="stylesheet" />
		<link href="css/header.css" rel="stylesheet" />
	</head>

	<body>
		<header class="mui-bar mui-bar-nav title">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left" style="color: white;"></a>
			<a class="mui-icon mui-icon-right-nav mui-pull-right" style="color: white;font-size: 16px;line-height: 25px;" id="changeNickname" style="">完成</a>
			<h1 class="mui-title title-color">修改昵称</h1>
		</header>
		
		<div class="mui-content">
			<div class="mui-input-row">
				<input type="text" class="mui-input-speech mui-input-clear" placeholder="新昵称" id="newNickName">
			</div>
			
		</div>
		
		<script src="js/mui.js"></script>
		<script src="js/app.js"></script>
		<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
		<script type="text/javascript">
			mui.init();
			mui.plusReady(function () {
				var userInfoStr = app.getGlobalUserInfo();
				var userInfo = JSON.parse(userInfoStr);
				// 设置原来的昵称
				var newNickName = document.getElementById("newNickName");
				newNickName.value = userInfo.nickname;
				
				// 向后台发送请求
				var changeNickname = document.getElementById("changeNickname");
				changeNickname.addEventListener("tap", function() {
					// 失去焦点
					newNickName.blur();
					var userInfoStr = app.getGlobalUserInfo();
					var userInfo = JSON.parse(userInfoStr);
					// 更新昵称
					var nickName = newNickName.value;
					
					if (!app.isNotNull(nickName)) {
						app.showToast("昵称不能为空", "error");
						return false;
					}
					// 判断是否修改过昵称
					if (nickName == userInfo.nickname) {
						app.showToast("昵称不能与原来的相同", "error");
						return false;
					} else {
						// 判断昵称长度
						if (nickName.length > 12) {
							app.showToast("昵称字数不能大于12", "error");
							return false;
						}
					}
					// 向后台发送请求
					plus.nativeUI.showWaiting("请稍后");
					mui.ajax(app.serverUrl + '/u/updateNickname', {
						data:{
							id: userInfo.id,
							nickname: nickName
						},
						dataType:'json',//服务器返回json格式数据
						type:'post',//HTTP请求类型
						timeout:10000,//超时时间设置为10秒；
						headers:{'Content-Type':'application/json'},	              
						success:function(data) {
							//服务器返回响应，根据响应结果，分析是否登录成功；
							console.log(JSON.stringify(data));
							plus.nativeUI.closeWaiting();
							if (data.code == 200) {
								// 登陆或注册成功,保存用户到本地缓存
								var userJson = data.data;
								app.setGlobalUserInfo(userJson);
								app.showToast("设置成功", "success");
								// 刷新index页面用户信息
								var webview = plus.webview.getWebviewById("wx-me.html");
								mui.fire(webview, "refresh");
								// 页面跳转
								mui.openWindow("index.html", "index.html");
							} else {
								app.showToast(data.msg, "error");
							}
						}
					});
				});
			});
		</script>
	</body>

</html>
